<template>
  <div class="component-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar 
      class="top-nav-bar" 
      @click-left="$router.back()" 
      fixed 
      placeholder
    >
      <template #left>
        <van-icon name="arrow-left" color="#000" class="icon" size="20"/>
        <span>确认订单</span>
      </template>
    </van-nav-bar>
    <!-- 收货地址 -->
    <div class="receive-address" @click="show = true">
      <div class="icon-loc">
        <van-icon name="location-o" />
      </div>
      <!-- <div>收货地址</div> -->
      <div class="address">收货地址：{{address.address}}</div>
      <div class="name-tel">
        <span class="name">{{address.name}}</span>
        <span class="tel">{{address.tel}}</span>
      </div>
      <div class="icon-arrow">
        <van-icon name="arrow" />
      </div>
    </div>
    <!-- 商品信息 -->
    <div class="goods-info" v-for="goodsInfo in goodsInfoArr" :key="goodsInfo.id">
      <div class="info-box">
        <!-- 商品图片 -->
        <div class="goods-pic">
          <img :src="goodsConstants.goodsPictureBaseURL + goodsInfo.goodsPicturePath" alt="">
        </div>
        <!-- 商品名 -->
        <div class="goods-name">
          <span>{{goodsInfo.goodsName}}</span>
        </div>
        <!-- 商品价格 -->
        <div class="goods-price">
          <span>￥{{goodsInfo.goodsPrice}}</span>
        </div>
        <!-- 购买数量 -->
        <div class="goods-number">
          <van-stepper v-model="goodsInfo.goodsNumber" @change="goodsNumberChange(goodsInfo.id, goodsInfo.goodsNumber)"/>
          <!-- <span>×{{goodsInfo.goodsNumber}}</span> -->
        </div>
      </div>
      <div class="info-box">
        <div class="freight">
          <span>配送服务：</span>
          <span>{{Number(goodsInfo.goodsFreight)==0 ? '免运费' : '运费 '+goodsInfo.goodsFreight}}</span>
        </div>
      </div>
      <div class="info-box">
        <div class="goods-param">
          <span>商品参数：</span>
          <span v-for="(param, index) in goodsInfo.goodsParam" :key="index">
            <span>{{index}}：</span>
            <span>{{param}}；</span>
          </span>
        </div>
      </div>
    </div>
    <!-- 提交订单 -->
    <van-submit-bar :price="sumPrice*100" button-text="提交订单" @submit="onSubmit" />
    <!-- 弹出框 -->
    <van-popup
      v-model="show"
      position="bottom"
      class="address-list"
    >
      <div class="receive-address" v-for="addr in addressArr" :key="addr.id" @click="address = addr; show = false">
        <div class="icon-loc">
          <van-icon name="location-o" />
        </div>
        <!-- <div>收货地址</div> -->
        <div class="address">收货地址：{{addr.address}}</div>
        <div class="name-tel">
          <span class="name">{{addr.name}}</span>
          <span class="tel">{{addr.tel}}</span>
        </div>
        <div class="icon-arrow">
          <van-icon name="arrow" />
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { Dialog, List, SubmitBar } from 'vant'
import { Popup } from 'vant'
import { Stepper } from 'vant'

export default {
  name: 'SubmitOrder',
  components: {
    [SubmitBar.name]: SubmitBar,
    [Popup.name]: Popup,
    [Stepper.name]: Stepper,
  },
  data() {
    return {
      goodsIds: [],
      goodsInfoArr: [],
      address: [],
      addressArr: [],
      show: false,
    }
  },
  computed: {
    // 计算总价
    sumPrice() {
      let sum = 0;
      this.goodsInfoArr.forEach((goodsInfo)=>{
        sum += Number(goodsInfo.goodsPrice) * Number(goodsInfo.goodsNumber) + Number(goodsInfo.goodsFreight)
      })
      return sum
    }
  },
  methods: {
    // 提交订单
    onSubmit() {
      this.$toast.loading({
        message: '订单提交中...',
        forbidClick: true,
      })
      let orderInfoArr = []
      let cartInfoIdArr = []
      let goodsInfoIdArr = []
      this.goodsInfoArr.forEach(goodsInfo=>{
        console.log(goodsInfo)
        let orderInfo = {}
        orderInfo['cartInfoId'] = goodsInfo.id  // 购物车信息编号
        orderInfo['orderStatus'] = false
        orderInfo['goodsNumber'] = goodsInfo.goodsNumber
        orderInfo['selectParam'] = JSON.stringify(goodsInfo.goodsParam)
        orderInfo['payMoney'] = Number(goodsInfo.goodsPrice) * Number(goodsInfo.goodsNumber) + Number(goodsInfo.goodsFreight)
        orderInfo['token'] = localStorage.getItem('token')
        orderInfo['goodsId'] = goodsInfo.goodsInfoId
        orderInfo['userReceiveAddressId'] = this.address.id
        console.log(orderInfo)
        orderInfoArr.push(orderInfo)
        cartInfoIdArr.push(goodsInfo.id)
        goodsInfoIdArr.push()
      })
      this.req.post(
        'user/add/order/',
        {
          orderInfoArr
        }
      ).then(res=>{
        this.$toast.clear()
        if (res.data.mark === 1) {
          this.$toast.success(res.data.message)
          Dialog.confirm({
            message: '是否支付订单',
          })
            .then(() => {
              // on confirm
              this.req.post(
                'user/pay/order/',
                {
                  orderInfoArr
                }
              ).then(res=>{
                if (res.data.mark === 1) {
                  this.$toast.success(res.data.message)
                  this.$router.back()
                } else {
                  this.$toast.fail('支付失败，请到用户中心完成订单支付')
                  this.$router.back()
                }
              }, err=>{
                  this.$toast.fail('支付失败，请到用户中心完成订单支付')
              })
            })
            .catch(() => {
              // on cancel
              this.$router.back()
            });
        } else {
          this.$toast.fail(res.data.message)
        }
      }, err=>{
        this.$toast.fail(err)
      })
    },
    // 商品数改变
    goodsNumberChange(userCartInfoId, goodsNumber) {
      // console.log(userCartInfoId, goodsNumber)
      this.req.post(
        'user/update/userCartInfo/',
        {
          userCartInfoId,
          goodsNumber
        }
      ).then(res=>{
        let data = res.data
        if ( data.mark === 1 ) {

        } else {
          this.$toast.fail(data.message)
        }
      }, err=>{
        this.$toast.fail(err)
      })
    },
  },
  created() {
    // 获取即将加入订单商品信息
    let goodsIds = this.$route.query.goodsIds
    this.goodsIds = this.$route.query.goodsIds
    localStorage.setItem('goodsIds', goodsIds)
    console.log(localStorage.getItem('goodsIds'))
    // goodsIds = localStorage.getItem('goodsIds')
    this.req.post(
      'user/get/userCartInfo/ids/',
      {
        goodsIds: localStorage.getItem('goodsIds')
      }
    ).then(res=>{
      if (res.data.mark === 1) {
        this.goodsInfoArr = res.data.data
      } else {
        this.$toast.fail(res.data.message)
      }
    }, err=>{
      this.$toast.fail(err)
    })
    // 获取用户默认收货地址
    this.req.post(
      'user/get/userReceiveAddressInfo/default/',
      {
        token: localStorage.getItem('token')
      }
    ).then(res=>{
      if (res.data.mark === 1) {
        this.address = res.data.data
      } else {
        this.$toast.fail(res.data.message)
        this.$router.push({name: 'addReceiveAddress'})
      }
    }, err=>{
      this.$toast.fail(err)
    })
    // 获取所有的收货地址
    this.req.post(
      'user/get/userReceiveAddressInfo/',
      {
        token: localStorage.getItem('token')
      }
    ).then(res=>{
      let data = res.data
      if (data.mark === 1) {
        this.addressArr = data.data
        this.addressArr = this.addressArr.sort((a, b)=>{
          return b.isDefault - a.isDefault
        })
      } else {
        this.$toast.fail(data.message)
      }
    }, err=>{
      this.$toast.fail(err)
    })
  }
}
</script>

<style lang="less" scoped>
.component-container {
  padding-bottom: 5rem;
}
// 收货地址
.receive-address {
  position: relative;
  margin: 0.5rem;
  padding: 0.5rem;
  height: 5rem;
  border-radius: 0.5rem;
  background-color: #fff;
  // 定位图标
  .icon-loc {
    position: absolute;
    top: 50%;
    left: 1rem;
    transform: translateY(-50%);
    font-size: 1.5rem;
  }
  // 箭头图标
  .icon-arrow {
    position: absolute;
    top: 50%;
    right: 1rem;
    transform: translateY(-50%);
    font-size: 1.5rem;
  }
  // 地址
  .address {
    position: absolute;
    top: 1rem;
    left: 3rem;
    overflow: hidden;
    font-weight: 600;
    text-overflow: ellipsis;
    /* 弹性伸缩盒子模型显示 */
    display: -webkit-box;
    /* 限制在一个块元素显示的文本的行数 */
    -webkit-line-clamp: 2;
    /* 设置或检索伸缩盒对象的子元素的排列方式 */
    -webkit-box-orient: vertical;
  }
  .name-tel {
    position: absolute;
    bottom: 1rem;
    left: 3rem;
    span {
      vertical-align: middle;
    }
    span:nth-child(1) {
      display: inline-block;
      margin-right: 0.5rem;
      max-width: 65%;
      /*1. 先强制一行内显示文本*/
      white-space: nowrap; 
      /*2. 超出的部分隐藏*/
      overflow: hidden;
      /*3. 文字用省略号替代超出的部分*/
      text-overflow: ellipsis;
    }
  }
}
// 商品信息
.goods-info {
  position: relative;
  margin: 0.5rem 0.5rem 0;
  padding: 0.5rem;
  border-radius: 0.5rem;
  background-color: #fff;
  .info-box {
    position: relative;
    padding: 0.5rem 0;
    border-bottom: 1px solid #eee;
    .goods-pic {
      overflow: hidden;
      width: 6rem;
      height: 6rem;
      border-radius: 1rem;
      img {
        width: 100%;
      }
    }
    .goods-name {
      position: absolute;
      top: 0.5rem;
      left: 7rem;
      overflow: hidden;
      text-overflow: ellipsis;
      /* 弹性伸缩盒子模型显示 */
      display: -webkit-box;
      /* 限制在一个块元素显示的文本的行数 */
      -webkit-line-clamp: 2;
      /* 设置或检索伸缩盒对象的子元素的排列方式 */
      -webkit-box-orient: vertical;
    }
    .goods-price {
      position: absolute;
      bottom: 1rem;
      left: 7rem;
      color: #ee0a24;
    }
    .goods-number {
      position: absolute;
      bottom: 1rem;
      right: 1rem;
      color: #999;
    }
  }
  
}
// 收货地址列表
.address-list {
  background-color: #eee;
  .receive-address:first-child {
    margin: 0.5rem 0.5rem 0;
  }
}
</style>